﻿<?php
/**
 * User Register
 *
 * Sewiki is a experimental software for course
 * Software Engineering in HIT and it's devoloped
 * upon CodeIgniter Framework. More infomation of
 * the framework, please vist http://codeigniter.com/
 *
 * @package  : CodeIgniter
 * @categroy : controllers/user
 * @author   : Oneplus <oneplus.lau@gmail.com>
 * @date     : 2011-06-22
 */
class Register extends CI_Controller {
	/**
	 * The constructor
	 *
	 * @access : public
	 * @return : void
	 */
	function __construct() {
		parent::__construct();
		$this->load->database();
	}
	
	public function index() {
		$this->regist();
	}

	/**
	 * Method regist
	 *
	 * call regist form and apply the regist logic
	 * 
	 * @access : public
	 * @param  : void
	 */
	public function regist() {
		$this->load->view('user/register');
		
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$confirm  = $this->input->post('confirm');
		$email    = $this->input->post('email');
		$interest = $this->input->post('interest');
		$quote    = $this->input->post('quote');
		
		if($this->input->post('regist')) {
			$this->load->model('user');
			if($this->user->existUser($username) || $this->user->existEmail($email)) {
				$sessiondata = array('msg' => '该用户已经存在');
				$this->session->set_userdata($sessiondata);
			}
			else {
				$userdata  = array(
					'username' => $username,
					'password' => md5($password),
					'email'    => $email,
					'role'     => 1,
					'quote'    => $quote);
				$interests = explode(' ', $interest);
				
				if($this->isLegalInterests($interests) == false) {
					$sessiondata = array('msg' => '用户兴趣过长，请不要搞破坏');
					$this->session->set_userdata($data);
				}
				else {
					$uid = $this->user->createUser($userdata);
					$this->user->createUserInterest($uid, $interests);
					$sessiondata = array(
						'uid'       => $uid,
						'role'      => 1,
						'logged_in' => true,
						'msg'       => '欢迎登陆 ' . $username);
						
					$this->session->set_userdata($sessiondata);
					redirect('main');
				}
			}
		}
	}
	
	private function isLegalInterests($interests) {
		foreach($interests as $interest) {
			if(strlen($interest) > 100) return false;
		}
		return true;
	}
}
?>